import { defineStore } from 'pinia'
import http from '@/tools/http'
import { toTree } from '@/tools/tree'
import type { Tree } from '@/tools/tree'

interface OrgInfoList {
    orgInfoList: OrgInfo[]
    orgInfoTree: Tree[]
}

interface OrgInfo {
    orgCode: string
    orgName: string
    orgStatus?: string
    orgType?: string
    orgSort?: number
    orgParent?: string
    remark?: string
}

export const useOrgStore = defineStore('org', {
    state: (): OrgInfoList => ({
        orgInfoList: [],
        orgInfoTree: []
    }),
    getters: {
        getOrgName: (state) => {
            return (orgCode: string | undefined) => {
                if (orgCode) {
                    for (let i = 0; i < state.orgInfoList.length; i++) {
                        if (state.orgInfoList[i].orgCode === orgCode) {
                            return state.orgInfoList[i].orgName
                        }
                    }
                }
                return ""
            }
        }
    },
    actions: {
        loadOrgInfo(orgInfoList?: OrgInfo[] | null) {
            if (!orgInfoList) {
                const orgInfoJson = sessionStorage.getItem("orgInfo")
                if (orgInfoJson && orgInfoJson !== "") {
                    this.orgInfoList = JSON.parse(orgInfoJson)
                    this.orgInfoTree = toTree(this.orgInfoList, "orgParent", null, "orgCode", "orgName", "orgCode")
                } else {
                    this.refreshOrgInfo()
                }
            } else {
                this.orgInfoList.length = 0;
                for (let i = 0; i < orgInfoList.length; i++) {
                    this.orgInfoList.push(orgInfoList[i])
                }
                this.orgInfoTree = toTree(this.orgInfoList, "orgParent", null, "orgCode", "orgName", "orgCode")
            }
        },
        refreshOrgInfo() {
            const request = { pageNum: 0, pageSize: 0 }
            http.post("/org/list", request).then(({ data }) => {
                if (data.code === "0") {
                    this.orgInfoList.length = 0;
                    for (let i = 0; i < data.data.length; i++) {
                        this.orgInfoList.push(data.data[i])
                    }
                    this.orgInfoTree = toTree(data.data, "orgParent", null, "orgCode", "orgName", "orgCode")
                    sessionStorage.setItem("orgInfo", JSON.stringify(this.orgInfoList))
                }
            })
        }
    }
})